package com.yyz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yyz.domain.Employee;
import com.yyz.common.R;
import com.yyz.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yyz
 * @create 2023-07-11 21:56
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("请求登录{}", employee);

        String password = employee.getPassword();
        //给密码进行md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        Employee emp = employeeService.login(employee);

        //如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("找不到该用户！");
        }

        if (!emp.getPassword().equals(employee.getPassword())) {
            return R.error("密码错误！");
        }

        //查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用!");
        }

        //登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());




        return R.success(emp);

    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R exit(HttpServletRequest request) {
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     * @param emp
     * @return
     */
    @PostMapping
    public R insert(@RequestBody Employee emp) {
        employeeService.insert(emp);

        return R.success("添加成功！");
    }

    /**
     * 分页查询员工信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageList(Integer page, Integer pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);
        IPage<Employee> pageInfo = employeeService.pageList(page, pageSize, name);

        return R.success(pageInfo);
    }

    /**
     * 禁用
     * @param emp
     * @return
     */
    @PutMapping
    public R forbidden(HttpServletRequest request,@RequestBody Employee emp){
        employeeService.forbidden(request,emp);

        return R.success(null);
    }

    /**
     * 根据id页面回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R update(@PathVariable Long id){
        Employee emp = employeeService.update(id);

        if (emp != null) {
            return R.success(emp);
        }

        return R.error("没有找到该数据！");
    }
}
